/**
 * Check 1 string is numberic
 **/
function isNumeric(input)
{
    return (input - 0) == input && (''+input).replace(/^\s+|\s+$/g, "").length > 0;
}

// form so sau khi lost focus
function formatNumber(obj)
{
    obj = $(obj);
    var fix = 0;

    if( obj.attr('fix') )
        fix = parseInt( obj.attr('fix') );

    obj.blur(function(){
        var v = obj.val( );

        if( v.length == 0 ) return false;

        if( v.indexOf( ',' ) > 0 ) return;

        v = v.replaceAll( '.', '').replaceAll( ',', '.');

        obj.val( formatMoney( parseFloat( v  ), fix ) );
    });
}

function formatMoney(num, fix) {

    if( num == 0 ) return num;

    var p = num.toFixed(fix);

    if( p < 1000 )  return (p + "").replace(".", ",");

    return  p.split("").reverse().reduce(function(acc, num, i, orig) {
        return  num + (i && !(i % 3) ? "." : "") + acc;
    }, "");
}


function formatDollar(num) {

    var p = num.toFixed(2).split(".");

    return  p[0].split("").reverse().reduce(function(acc, num, i, orig) {
        return  num + (i && !(i % 3) ? "," : "") + acc;
    }, "");
}


/*
*  ajax_post_update : Update data to server with post method
*  @param
*  url: Url to post data
*  data: Data - use  serialize : var data = $('form_id').serialize()
*  succ_message: String - message content show after post success
*  update: Container update response data after success
*          - sample: #contain, jQuery('#contain')
*
*  use : ajax_post_update('/locations/update', 'id=10&text=Michael', 'updated success', jQuery('#update'))
*/

function postAjax(url, data, callback){

    return $.ajax({
        url: url,
        data: data,
        dataType: json,
        async: true,
        type: 'POST',

        complete: function(){
        },
        success: function(msg){
            if (typeof(callback) === "function") {
                callback(msg);
            }
        },
        statusCode: {
            401: function(){
            }
        },
        error: function(xhr, status, err){
        }
    });
}

/**
* Load ajax request: this function use to load content from server
*
* params:
*   - url: url request content
*   - async : true, false
*/

function getAjax(url, async, callback, datatype, loading )
{
	if(typeof(datatype) == 'undefined') datatype = 'json';
	
    jQuery.ajax(
    {   url: url,
        type: 'GET',
        dataType: datatype,
        cache:true,
        success: function(msg)
        {
            var $msg = jQuery(msg);

            if( typeof( callback ) === "function" )
            {
                callback(msg);
            }
            else
            	return msg;
        },

        error: function(xhr, status, err) {
            if (xhr.status == 401){}
                //window.location.href = '/login';
            return xhr;
        },

        beforeSend:function()
        {
            if( loading ) {}
        },
        async:async,

    });
}


/**
*  clear_form_elements: Clear data of controls of form
*
*  params: from id - #form1
*/
  function clear_form_elements(ele) {

      $(ele).find(':input').each(function () {
          switch (this.type) {
              case 'password':
              case 'select-multiple':
              case 'select-one':
              case 'text':
              case 'textarea':
                  $(this).val('');
                  break;
              case 'checkbox':
              case 'radio':
                  this.checked = false;
          }
      });

 }

 /**
 * Select all checkbox
 *
 * params:
 *   flag: true-> check all; false -> uncheck all
 *   parent: element contains all check box
 */
 function select_all(flag, parent)
 {
     if( parent = null )
     {
         parent = jQuery(document);
     }
     if( flag )
     {
         jQuery(':checkbox', parent).attr('checked', 'checked' );
     }
     else
     {
         jQuery(':checkbox', parent).removeAttr('checked' );
     }
 }

 /**
 * Show message for js
 *
 * params:
 *   friend id: string
 */
var _global_message;
var _global_message_timer;

function show_message( text, type )
{
	if( typeof(_global_message) == 'undefined')
		_global_message = $('#global_message');
    if( type == "S" ) return; // ko hien thi nhung message thanh cong
    clearTimeout( _global_message_timer );

    jQuery('.alert', _global_message).html(text);
    _global_message.show();

    _global_message_timer = setTimeout( hide_message, 5000);
}

function hide_message( )
{
    clearTimeout( _global_message_timer );
    _global_message.hide();
}


function closeFloatWindow(obj, selector, remove )
{

    var target = selector;
    if( target == null )
    {
        target = $(obj);
    }
    else if( typeof(target) !== 'object' )
        target = $(obj).closest(selector);

    if( target != null  )
    {
        // target.fadeOut("fast", function(){ if( remove ) target.remove(); } );
        if( remove )
            target.remove();
        else
            target.addClass('hide').hide();

        target.prev().remove();
    }
    return false;
}

// format to money
Number.prototype.formatMoney = function(c, d, t){
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

/**
 * Replaces all instances form @param:'strTarget' to @param:'strSubString' of the given substring.
 *
 * @param: strTarget is string or array()
 * @param: strSubString
 *
 **/
String.prototype.replaceAll = function( strTarget,  strSubString ){
	var strText = this;

	if($.isArray(strTarget)) {
		strTarget.forEach(function(val, i){
			strText = strText.replaceAll(val, strSubString);
		});
		return( strText );
	} else {
	    var intIndexOfMatch = strText.indexOf( strTarget );

	    // Keep looping while an instance of the target string
	    // still exists in the string.
	    while (intIndexOfMatch != -1){
		    // Relace out the current instance.
		    strText = strText.replace( strTarget, strSubString )

		    // Get the index of any next matching substring.
		    intIndexOfMatch = strText.indexOf( strTarget );
	    }

	    // Return the updated string with ALL the target strings
	    // replaced out with the new substring.
	    return( strText );
	}
}
